package com.yt.setclaim.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yt.setclaim.models.entity.ClaimCalc;
import com.yt.setclaim.models.entity.MedicalReview;
import com.yt.setclaim.models.service.ClaimCalcService;
import com.yt.setclaim.models.vo.MedicalReviewVO;
import com.yt.setclaim.server.mapper.ClaimCalcMapper;
import com.yt.setclaim.server.mapper.MedicalReviewMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ClaimCalcServiceImpl extends ServiceImpl<ClaimCalcMapper, ClaimCalc> implements ClaimCalcService {
    
    private final MedicalReviewMapper medicalReviewMapper;
    
    public ClaimCalcServiceImpl(MedicalReviewMapper medicalReviewMapper) {
        this.medicalReviewMapper = medicalReviewMapper;
    }
    
    @Override
    public ClaimCalc getByReviewId(Integer reviewId) {
        return this.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ClaimCalc>()
                .eq("review_id", reviewId)
                .eq("is_delete", 0));
    }

    @Override
    public List<MedicalReviewVO> getPendingReviews() {
        // 获取所有已审核通过但未核算的医疗审核记录
        // 1. 首先获取所有审核通过的医疗审核记录
        QueryWrapper<MedicalReview> reviewQueryWrapper = new QueryWrapper<>();
        reviewQueryWrapper.eq("review_result", "通过"); // 审核通过
        reviewQueryWrapper.eq("is_delete", 0); // 未删除
        List<MedicalReview> medicalReviews = medicalReviewMapper.selectList(reviewQueryWrapper);
        
        // 2. 过滤掉已经进行过核算的记录
        List<MedicalReviewVO> pendingReviews = new ArrayList<>();
        for (MedicalReview review : medicalReviews) {
            // 检查是否已经核算过
            ClaimCalc existingCalc = this.getOne(new QueryWrapper<ClaimCalc>()
                    .eq("review_id", review.getReviewId())
                    .eq("is_delete", 0));
            
            // 如果还没有核算，则添加到待核算列表中
            if (existingCalc == null) {
                MedicalReviewVO vo = new MedicalReviewVO();
                BeanUtils.copyProperties(review, vo);
                // ID转换为字符串类型
                vo.setReviewId(String.valueOf(review.getReviewId()));
                vo.setClaimId(String.valueOf(review.getClaimId()));
                vo.setAdminId(String.valueOf(review.getAdminId()));
                pendingReviews.add(vo);
            }
        }
        
        return pendingReviews;
    }
}